package com.xiaohudie.servier.Impi;

import com.xiaohudie.config.RedisConfig;
import com.xiaohudie.mapper.MiaoShaMapper;
import com.xiaohudie.mapper.OrderMapper;
import com.xiaohudie.pojo.*;
import com.xiaohudie.servier.MiaoShaServicer;
import com.xiaohudie.util.RedisIdWork;
import com.xiaohudie.util.SimpleLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Author xiao hu die
 * @Date 2022/3/6 15:25
 * @Version 1.0
 */
@Service
public class MiaoShaServicerImpl implements MiaoShaServicer {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private MiaoShaMapper miaoShaMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RedisIdWork redisIdWork;
    @Resource
    private RedissonClient redissonClient;
    @Override
    @Transactional
    public  synchronized  AjaxResult  queryById(Integer id) {
        /**得到用户信息*/
        User user = MyThreadLocal.getUser();
        /**查询出优惠券的单体信息*/
        YouHuiQuan youHuiQuan = miaoShaMapper.queryById(id);
        /**判断时间是否开始*/
        /** if ( youHuiQuan.getBeginTime().isAfter(LocalDateTime.now()) || youHuiQuan.getEndTime().isBefore(LocalDateTime.now())){
         return AjaxResult.error("秒杀尚未开始");
         }*/
        /**判断库存是否开始*/
        if (youHuiQuan.getKuCun() < 1) {
            return AjaxResult.error("优惠券已卖完");
        }
        /**实现一人一单*/
        // SimpleLock simpleLock = new SimpleLock("order:" + user.getId(), stringRedisTemplate);
        // boolean b = simpleLock.tryLock(100);

            RLock redisLock = redissonClient.getLock("lock:order:" + user.getId());
        try {
            boolean b = redisLock.tryLock();
            if (false == b) {
                return AjaxResult.error("请勿重复购买");
            }
            /**开始买优惠券
             * 库存减1*/
            Integer integer = miaoShaMapper.updatekuCun(id);
            /**判断Integer的值是否为0*/
            if (integer == 0) {
                return AjaxResult.error("已卖完");
            }
            /**开始向订单表中添加订单信息*/
            Order order = new Order();
            order.setId(redisIdWork.nextId("chengweiyi"));
            order.setUserId(Integer.valueOf(user.getId()));
            order.setYouhuiquanId(youHuiQuan.getId());
            orderMapper.OrderInsert(order);
            return AjaxResult.success("抢购成功:订单id为:" + order.getId());
          } finally {
            /**释放锁*/
            //simpleLock.unlock();
            redisLock.unlock();
        }
    }


}
